package com.djicorp.rm.web.api.common;

import cn.hutool.core.lang.Validator;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

/**
 * Spring上下文持有工具类(支持Spring Boot自动装配)
 */
@Slf4j
@Component
@Lazy(false) // 禁用延迟加载
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {

    private static ApplicationContext applicationContext = null;

    public static<T> T getBeanByClassSimpleName(String simpleName) {
        return (T) applicationContext.getBean(lowerFirst(simpleName));
    }

    public static String lowerFirst(String oldStr){
        char[] chars = oldStr.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }

    // 实现ApplicationContextAware接口的上下文注入方法
    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        if (applicationContext != null) {
            log.warn("SpringContextHolder中的ApplicationContext被覆盖，原上下文：{}", applicationContext);
        }
        applicationContext = ctx;
    }

    /**
     * 获取Spring应用上下文
     */
    public static ApplicationContext getApplicationContext() {
        assertContextInjected();
        return applicationContext;
    }

    /**
     * 根据Bean名称获取对象
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        assertContextInjected();
        return (T) applicationContext.getBean(name);
    }

    /**
     * 根据Bean类型获取对象
     */
    public static <T> T getBean(Class<T> clazz) {
        assertContextInjected();
        return applicationContext.getBean(clazz);
    }

    /**
     * 清除上下文引用
     */
    public static void clearHolder() {
        log.debug("清除SpringContextHolder的ApplicationContext：{}", applicationContext);
        applicationContext = null;
    }

    /**
     * 实现DisposableBean接口的销毁方法
     */
    @Override
    public void destroy() throws Exception {
        clearHolder();
    }

    /**
     * 上下文注入状态校验
     */
    private static void assertContextInjected() {
        Validator.validateTrue(applicationContext != null,
                "ApplicationContext未注入，请检查以下配置：\n"
                        + "1. Spring Boot项目需在启动类添加@Bean\n"
                        + "2. XML配置需定义<bean class=\"完整包路径.SpringContextHolder\"/>");
    }
}